package com.wdy.ssafe;

import com.wdy.servicebase.utils.R;
import com.wdy.servicebase.utils.ResponseUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

@Slf4j
public class TokenLogoutHandeler implements LogoutHandler {

  private RedisTemplate<String, Object> redisTemplate;
  private TokenManager tokenManager;

  public TokenLogoutHandeler(
      RedisTemplate<String, Object> redisTemplate, TokenManager tokenManager) {
    this.redisTemplate = redisTemplate;
    this.tokenManager = tokenManager;
  }

  @Override
  public void logout(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {
    String token = request.getHeader("token");
    if(!StringUtils.isEmpty(token)){
      try {
        String userName = tokenManager.parseToken(token);
        redisTemplate.delete(userName);

        ResponseUtil.out(response, R.ok());
      } catch (Exception e) {
        log.info("登出时解析 token 异常, token: {}", token);
        return;
      }
    }

    // 从 hander 里解析 token

    // token 不为空，删除 token

  }
}
